// pages/garage/secondBatch/secondBatch.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        carId:'',
        publishCar:{
            secondBatchPrice:'',
            depositAmount:'',
            label:'',
            videoList:[],
            picList:[],
            reportList:[]
        },
        carInfo:{},
        labelList:['割肉价','一口价','仅限同城','极品车况','诚意私聊','仅限车商'],
        canSub:false,
        secondBatchId:'',
        depositAmountLabelList: [500, 1000, 2000],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    doNothing(){},
    onLoad: function (options) {
        // 必须一个车辆的ID
        if(undefined != options.cid){
            let self = this;
            this.setData({
                'carId': options.cid
            },()=>{
                self.InitUserStatus();
            })
            wx.enableAlertBeforeUnload({
                message: "确定要放弃当前填写内容嘛？",
                success: function (res) {
                },
                fail: function (errMsg) {
                },
            });
        }else{
            app.showNoAuthOrNoGrant('未找到您要查看的车辆哦~');
        }
    },
    // 检查一下登录状态。
    async InitUserStatus(){
        app.showLoading("获取用户信息");
        await app.checkToken();
        this.InitUserInfo();
        wx.hideLoading();
    },
    InitUserInfo(){
        this.setData({
            'userInfo': app.globalData.userInfo
        });
        // 加载车辆信息。
        this.carManageDetail();
    },
    // changeIcon(e){
    //     this.setData({
    //         'publishCar.label': e.currentTarget.dataset.item
    //     });
    //     this.validSubParams();
    // },
    changeIcon(e) {
      let name = e.currentTarget.dataset.name;
      let item = e.currentTarget.dataset.item;
      let publishCar = this.data.publishCar;
      publishCar[name] = item;
      this.setData({
        'publishCar': publishCar
      });
      this.validSubParams();
    },
    carManageDetail(){
        if (null != app.globalData.atttionCar) {
            this.setData({
                'carInfo': app.globalData.atttionCar
            });
        }else{
            app.sHttp.carManageDetail(this.data.carId).then(res =>{
                res.result.imageList = [];
                res.result.carPicList.forEach(item =>{
                    res.result.imageList.push(item.picUrl);
                })
                this.setData({
                    'carInfo': res.result
                });
            },err=>{
                app.error(err.msg);
            })
        }
    },
    validSubParams(){
        let yuan = {
            secondBatchPrice:'',
            depositAmount:'',
            label:''
        };
        let publishCar = this.data.publishCar;
        let canSub = true;
        for (const key in publishCar) {
            if (Object.hasOwnProperty.call(publishCar, key) && Object.hasOwnProperty.call(yuan, key)) {
                if (yuan[key] == publishCar[key]) {
                    canSub = false;
                }
            }
        };
        this.setData({
            'canSub': canSub
        });
        return canSub;
    },
    publishCarInput(e){
        let publishCar = this.data.publishCar;
        publishCar[e.currentTarget.dataset.name] = e.detail.value;
        this.setData({
            'publishCar':publishCar
        });
        this.validSubParams();
    },
    BackPage() {
        wx.disableAlertBeforeUnload({
            success: function (res) {
            },
            fail: function (errMsg) {
            },
        });
        var that = this;
        wx.navigateBack({
          delta: 1,
          fail: function(){
            that.toHome();
          }
        });
    },
    toHome(){
        wx.disableAlertBeforeUnload({
            success: function (res) {
            },
            fail: function (errMsg) {
            },
        });
    wx.reLaunch({
        url: '/pages/home/home',
    })
    },
    // 提交一口价
    submitCar(){
        if (this.validSubParams()) {
            let self = this;
            let publishCar = app.deepCopy(self.data.publishCar);
            let canshuList = ['videoList','picList','reportList'];
            let cansub = true;
            canshuList.forEach(item =>{
                publishCar[item].forEach(items =>{
                    if (items.url.indexOf('tmp') != -1 || items.url.indexOf('wxfile') != -1) {
                      cansub = false;
                    }
                });
            })
            if(!cansub){
              app.alert('请等待所有文件上传完毕');
              return;
            }
            publishCar.carId = self.data.carId || self.data.carInfo.carId
            let that = self;
            app.sHttp.secondBatchPublish(publishCar).then(res => {
                wx.hideLoading();
                let secondBatchId = res.secondBatchId;
                that.setData({
                    'secondBatchId':secondBatchId
                });
                let that_ = that;
                wx.showModal({
                    title: '发布完成',
                    content: '您的一口价发布成功',
                    confirmText:'我知道了',
                    cancelText:'前往查看',
                    success (res) {
                      if (res.confirm) {
                        that_.BackPage();
                      } else if (res.cancel) {
                        that_.seeNewPage();
                      }
                    }
                })
            },err =>{
                app.error(err.msg||err);
            })
        }else{
            app.alert('请填写完整信息后发布');
        }
    },
    seeNewPage(){
        wx.disableAlertBeforeUnload({
            success: function (res) {
            },
            fail: function (errMsg) {
            },
        });
        wx.redirectTo({
          url: '/pages/me/secondBatch/secondBatch',
        })
    },
    showModal(e) {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    },
    hideModal(e) {
      this.setData({
        modalName: null
      })
    },
    // 选择 微信 的文件
    chooseWxFile(e){
        let type = e.currentTarget.dataset.type;
        console.log('tryoe',type);
        let self = this;
        wx.chooseMessageFile({
            count: 9,
            type: type,
            success (res) {
                const tempFilePaths = res.tempFiles;
                let videoList = self.data.publishCar.videoList;
                let picList = self.data.publishCar.picList;
                let reportList = self.data.publishCar.reportList;
                tempFilePaths.forEach( item =>{
                    if('video' == type){
                        videoList.push({
                            type:item.type,
                            url:item.path
                        })
                    }
                    if('image' == type){
                        picList.push({
                            type:item.type,
                            url:item.path
                        })
                    }
                    if('file' == type){
                        reportList.push({
                            type:item.type,
                            url:item.path
                        })
                    }   
                })
                self.setData({
                    'publishCar.videoList': videoList,
                    'publishCar.picList': picList,
                    'publishCar.reportList': reportList
                });
                self.uploadTheImage(type);
            }
        })
    },
    uploadFiles(){
        let publishCar = this.data.publishCar;
        let canshuList = ['videoList','picList','reportList'];
        let promiseList = [];
        app.showLoading('提交中');
        canshuList.forEach(item =>{
            let noUploadReq = [];
            publishCar[item].forEach(items =>{
                if (items.url.indexOf('tmp') != -1 || items.url.indexOf('wxfile') != -1) {
                  promiseList.push(app.sHttp.upload({'filePath':items.url,'fileType':'carArchives','isNeedThumbnail':0}));
                }else{
                  noUploadReq.push(items);
                }
            });
            publishCar[item] = noUploadReq;
        })
        let self = this;
        return new Promise(function(resolve, reject) {
            if (promiseList.length > 0) {
                let that = self;
                Promise.all(promiseList).then((result) => {
                    let videoListSize = publishCar['videoList'].length;
                    let picListSize = publishCar['picList'].length;
                    publishCar['videoList'].forEach((isItem,isIndex) =>{
                        isItem.url = result[isIndex].originalUrl;
                    });
                    publishCar['picList'].forEach((isItem,isIndex) =>{
                        isItem.url = result[videoListSize+isIndex].originalUrl;
                    });
                    publishCar['reportList'].forEach((isItem,isIndex) =>{
                        isItem.url = result[videoListSize+picListSize+isIndex].originalUrl;
                    });
                    that.setData({
                        'publishCar.videoList': publishCar['videoList'],
                        'publishCar.reportList': publishCar['reportList'],
                        'publishCar.picList': publishCar['picList']
                    })
                    wx.hideLoading();
                    resolve(true)
                }).catch((error) => {
                    wx.hideLoading();
                    reject(error)
                })
            }else{
                wx.hideLoading();
                resolve(true)
            }
        })
    },
    
    uploadTheImage(type){
      let imgList = [];
      if('video' == type){
        imgList = this.data.publishCar.videoList;
      }
      if('image' == type){
        imgList = this.data.publishCar.picList;
      }
      if('file' == type){
        imgList = this.data.publishCar.reportList;
      };
      imgList.forEach(async (items,index) =>{
        let filePath = items.url+"";
        if (filePath.indexOf('tmp') != -1 || filePath.indexOf('wxfile') != -1) {
          // 压缩一下再上传
          if(filePath.substring(filePath.length-3) == 'jpg'){
            const compressImage = app.promisify(wx.compressImage);
            console.log(filePath);
            const res = await compressImage({
              src: filePath, // 图片路径
              quality: 67 // 压缩质量
            });
            filePath = res.tempFilePath;
          } 
          let self = this;
          app.sHttp.upload({'filePath':filePath,'fileType': 'carArchives','isNeedThumbnail':0}).then(res=>{
            imgList[index].url = res.originalUrl;
            if('video' == type){
              self.setData({
                'publishCar.videoList': imgList
              })
            }
            if('image' == type){
              self.setData({
                'publishCar.picList': imgList
              })
            }
            if('file' == type){
              self.setData({
                'publishCar.reportList': imgList
              })
            }
          },err=>{
            app.error(err.msg);
          })
        }
      })
    },
    DelImg(e){
      wx.showModal({
        title: '删除确认',
        content: '确定要删除这张图片嘛？',
        cancelText: '取消',
        confirmText: '删除',
        success: res => {
          if (res.confirm) {
            let params = e.currentTarget.dataset.type;
            let publishCar = this.data.publishCar;
            publishCar[params].splice(e.currentTarget.dataset.index, 1);
            this.setData({
              publishCar: publishCar
            })
          }
        }
      })

    },
})